<template>
  <canvas id="yuvCanvas" width="640" height="480"></canvas>
</template>

<script>
import Yuv2rgbPlayer from '@/utils/player.js';

export default {
  data() {
    return {
      ws: null,
      yuvCanvas: null,
      player: null,
    };
  },
  mounted() {
    this.initWebSocket();
  },
  methods: {
    initWebSocket() {
      let that = this;
      this.ws = new WebSocket('ws://localhost:8081');
      this.ws.binaryType = 'arraybuffer';
      const canvas = document.getElementById('yuvCanvas');
      this.player = new Yuv2rgbPlayer(canvas);
      this.ws.binaryType = 'arraybuffer';  // 确保接收二进制数据

      // WebSocket 接收消息
      this.ws.onmessage = function(event) {
        let frameData = new Uint8Array(event.data);
        that.player.renderFrame(frameData, 640, 480, '420-yuv');
      };

      this.ws.onerror = function(error) {
        console.error('WebSocket Error:', error);
      };

      this.ws.onopen = function() {
        console.log('WebSocket connection established');
        // 可以在这里发送任何初始消息或设置
      };

      this.ws.onclose = function() {
        console.log('WebSocket connection closed');
      };
    },
  }
};
</script>
